﻿using System.Net.Http.Json;
using Blazored.LocalStorage;
using System.Security.Claims;
using BlazorLearn.Shared.Models;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Components.Authorization;

namespace BlazorLearn.Shared.Services;
public class AuthenticationServiceProvider : AuthenticationStateProvider, IAuthenticationService
{
    private readonly HttpClient _client;
    private readonly ILocalStorageService _localStorageService;

    public AuthenticationServiceProvider(HttpClient client,
                                         ILocalStorageService localStorageService)
    {
        this._client = client;
        this._localStorageService = localStorageService;
    }

    public virtual async Task SignInAsync(LoginViewModel model)
    {
        var response = await _client.PostAsJsonAsync("/api/authentication/token", model);
        response.EnsureSuccessStatusCode();
        var token = await response.Content.ReadAsStringAsync();

        //Redis, Cookie, LocalStorage, ...

        await StoreTokenAsync(token);
    }

    protected virtual async Task StoreTokenAsync(string token)
    {
        await _localStorageService.SetItemAsStringAsync("token", token);
    }

    protected virtual async Task<string> RestoreTokenAsync()
    {
         return await _localStorageService.GetItemAsStringAsync("token");
    }

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        ClaimsPrincipal principal = new();
        var token = await RestoreTokenAsync();
        if (!string.IsNullOrWhiteSpace(token))
        {
            //解析 token
            JwtSecurityTokenHandler handler = new();
            var jwtToken= handler.ReadJwtToken(token);

            var claims = jwtToken.Claims;
            var identity = new ClaimsIdentity(claims,"api");
            principal.AddIdentity(identity);
        }

        return new(principal);
    }
}
